/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* head = nullptr;
        ListNode* tail = nullptr;
        ListNode *cur1 = l1, *cur2 = l2;
        int t = 0;
        while (cur1 && cur2) {
            int sum = cur1->val + cur2->val + t;
            ListNode* newnode = new ListNode(sum % 10);
            if (head == nullptr) {
                head = tail = newnode;
            } else {
                tail->next = newnode;
                tail = newnode;
            }
            t = sum / 10;
            cur1 = cur1->next;
            cur2 = cur2->next;
        }
        if (cur1) {
            while (cur1) {
                int sum = cur1->val + t;
                ListNode* newnode = new ListNode(sum % 10);
                tail->next = newnode;
                tail = newnode;
                t = sum / 10;
                cur1 = cur1->next;
            }
        }
        if (cur2) {
            while (cur2) {
                int sum = cur2->val + t;
                ListNode* newnode = new ListNode(sum % 10);
                tail->next = newnode;
                tail = newnode;
                t = sum / 10;
                cur2 = cur2->next;
            }
        }
        if (t) {
            ListNode* newnode = new ListNode(t);
            tail->next = newnode;
            tail = newnode;
        }
        return head;
    }
};